import { WarningOutlined } from "@ant-design/icons";
import notify from "devextreme/ui/notify";
import React, { useEffect, useRef, useState } from "react";
import { history, useModel } from 'umi';
import { DevPopup } from '~/public/cpas-ui';
import AntTabs from '~/public/cpas-ui/components-ui/ant-components/AntTab';
import CommonCpasTable from "../components/CommonCpasTable";
import FullNamePupop from "../components/CommonCpasTable/fullNamePupop";
import PageLoading from "../components/PageLoading";
import "./index.less";
import { getSeekAuditReportTemplate, getfindDesignTableName, getjudgmentInit, gettableIsVerifyList, templateInitApi } from "./service";

// import { Tabs } from 'antd';
const ApprovedFinance = (props: any) => {
    const { initialState,setInitialState } = useModel('@@initialState');


  // pageType 现在通过菜单点击时全局设置到 sessionStorage，DesignTableApi.js 会直接从 sessionStorage 获取
  


    const { dbname, zcbfid, bsdw } = initialState?.curPart as API.CurPart;
    const [valIndex, setValIndex] = useState<string>('1');
    const [spinLoad, setSpinLoad] = useState<boolean>(false);
    const [spinAntTabs, setSpinAntTabs] = useState<boolean>(true);
    const [isInitBtn, setIsInitBtn] = useState<boolean>(true);
    const refFullNamePupop = useRef<any>();

    let tableNameGroup = ['审定财务-资产表', '审定财务-负债表', '审定财务-利润表',
        '审定财务-现金流量表', '审定财务-现金流补充资料表', '审定财务-所有者权益变动表_本年', '审定财务-所有者权益变动表_上年', '审定财务-资产减值准备情况表'];
    const [excelParams, setExcelParams] = useState<any>([
        {
            cpastableParam: {
                tname: "审定财务-资产表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "资产负债表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-负债表",
                data_id: "",
                type: "fs",
            },
            // // tableTitle: "资产负债表（续）",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-利润表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "利润表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-现金流量表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-现金流补充资料表",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "现金流量表补充资料",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            isBatchExport: false
        },
        {
            cpastableParam: {
                tname: "审定财务-所有者权益变动表_本年",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "股东(或所有者)权益变动表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            // isColumnNum: true,: true,
            isBatchExport: true
        },
        {
            cpastableParam: {
                tname: "审定财务-所有者权益变动表_上年",
                data_id: "",
                type: "fs",
            },
            // tableTitle: "股东(或所有者)权益变动表",
            tableDate: " ",
            isExportTableTitle: true,
            exportType: "primary",
            // isColumnNum: true,: true,
            isBatchExport: true
        },

    ]);
    const { pathname, query }: any = window.location || {};

    const [antTabsData, setAntTabsData] = useState<any[]>([
        {
            tabName: '资产',
            tabKey: '1',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-资产表',
                titleName: '资产负债表',
                WscwbbType: '资产类',
                origin: '审定财务',
                tabsIndex: 1,
            }
        },
        {
            tabName: '负债',
            tabKey: '2',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-负债表',
                titleName: '资产负债表（续）',
                WscwbbType: '负债类',
                origin: '审定财务',
                tabsIndex: 2,
            }
        },
        {
            tabName: '利润',
            tabKey: '3',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-利润表',
                titleName: '利润表',
                WscwbbType: '利润类',
                origin: '审定财务',
                tabsIndex: 3,
            }
        },
        {
            tabName: '现流',
            tabKey: '4',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-现金流量表',
                titleName: '现金流量表',
                WscwbbType: '现金流量类',
                origin: '审定财务',
                tabsIndex: 4,
            }
        },
        {
            tabName: '现流附',
            tabKey: '5',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-现金流补充资料表',
                titleName: '现金流量表补充资料',
                WscwbbType: '现金流补充资料类',
                origin: '审定财务',
                tabsIndex: 5,
                actionCol: 2,
            }
        },
        {
            tabName: '权益变动(本年)',
            tabKey: '6',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-所有者权益变动表_本年',
                titleName: '所有者权益变动表',
                WscwbbType: '所有者权益变动表',
                origin: '审定财务',
                tabsIndex: 6,
            }
        },
        {
            tabName: '权益变动(上年)',
            tabKey: '7',
            isVerify: false,
            closable: false,
            propsData: {
                tableName: '审定财务-所有者权益变动表_上年',
                titleName: '所有者权益变动表(续)',
                WscwbbType: '所有者权益变动表(上年)类',
                origin: '审定财务',
                tabsIndex: 7,
            }
        }
    ]);
    const [hideAddBtn, setHideAddBtn] = useState<boolean>(false);
    const refsCommonCpasTable = useRef<any>(null);
    const refsDelte = useRef<any>(1);

    const changeTabsKey = (val: string) => {
        setIsInitBtn(false);
        setValIndex(val);
        history.push('/ReportSys/approvedFinance');

    };

    const changeTabs = (changeCur: string) => {
        antTabsData.forEach(item => {
            if (item.propsData.tableName === changeCur) {
                setValIndex(item.tabKey);
            }
        });
    }
    const remove = async (targetKey: any) => {
        // console.log(targetKey);
        // 暂时写死
        await refsCommonCpasTable.current.clearDesignTableName('审定财务-资产减值准备情况表');
        setAntTabsData((item) => {
            let lastIndex: any;
            const tempData = [...item];
            tempData.forEach((pane, i) => {
                if (pane.tabKey === targetKey) {
                    lastIndex = i - 1;
                }
            });
            const newData = tempData.filter(pane => pane.tabKey !== targetKey);

            if (newData.length && valIndex === targetKey) {
                if (lastIndex >= 0) {
                    setValIndex(newData[lastIndex].tabKey);
                } else {
                    setValIndex(newData[0].tabKey);
                }
            }
            return newData;
        });


        // setExcelParams((item: any) => {
        //     const tempData = [...item];
        //     const newData = tempData.filter(pane => pane.tabKey !== targetKey);
        //     return newData;
        // });

        window.localStorage.setItem(`审定财务-资产减值准备情况表-${dbname}`, JSON.stringify({
            isADD: false
        }));
        setHideAddBtn(false);
        notify(`删除资产减值标签页，成功！`, "success", 2000);

    };
    const getDesignTableName = async (funType: string) => {
        let indexD = -1;
        indexD = antTabsData.findIndex((item) => item.propsData.tableName === '审定财务-资产减值准备情况表');
        const res = await getfindDesignTableName({ design_tableName: '审定财务-资产减值准备情况表', dbname });
        if (res.success) {
            if (res.data || funType === 'addTabs') {
                if (indexD < 0) {
                    setAntTabsData((item) => {
                        const newData = [...item];
                        newData.push({
                            tabName: '减值准备',
                            tabKey: '8',
                            isVerify: false,
                            closable: true,
                            propsData: {
                                tableName: '审定财务-资产减值准备情况表',
                                titleName: '资产减值准备情况表',
                                WscwbbType: '资产减值准备情况类',
                                origin: '审定财务',
                                tabsIndex: 8,
                            }
                        });
                        return newData;
                    });
                    window.localStorage.setItem(`审定财务-资产减值准备情况表-${dbname}`, JSON.stringify({
                        isADD: true
                    }));
                    if (funType === 'addTabs') {
                        setValIndex('8');
                    }
                }
                setHideAddBtn(true);
            } else {
                if (indexD > 0) {
                    remove('8');
                }
            }
        }
    };
    const antTabsDetail = async () => {
        const res = await gettableIsVerifyList({ tableName: "审定财务", dbname, isTid: false });
        if (res.success) {
            if (res.data.length > 0) {
                const tempsName = res.data.map((item: { name: string }) => item.name).join(',') || "";
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        const msg = item.propsData.tableName;
                        const isName = tempsName.includes(msg);
                        item.isVerify = isName;
                        return item;
                    });
                    return newData;
                });
            } else {
                setAntTabsData((oldData: any) => {
                    const newData = [...oldData];
                    newData.forEach((item: any) => {
                        item.isVerify = false;
                        return item;
                    });
                    return newData;
                });
            }
        } else {
            notify(`获取isVerify校验失败！`, "error", 2000);
        }
    }
    const getAuditReportTemplate = async (isAllInit: boolean, yearTableName: any, actionTabs: any) => {
        try {
            const judg = await getjudgmentInit({
                dbname,
                type: 'fs',
                tableRealName: yearTableName
            });
            if (judg.success) {
                console.log(refsCommonCpasTable.current, '@@@ ');
                if (judg.data?.count_number === 0) {
                    setSpinLoad(true);
                    const res = await getSeekAuditReportTemplate({
                        zcbfid
                    });
                    if (res.success) {
                        let tempObjs: any = {};
                        if (isAllInit) {
                            tempObjs = {
                                tableNames: tableNameGroup,
                            }
                        } else {
                            tempObjs = {
                                tableNames: ["审定财务-资产减值准备情况表"],
                                opt: {
                                    duplicate: "cover"
                                }
                            }
                        }
                        const resTemp: any = await templateInitApi({
                            dbName: dbname,
                            templateName: res.data.AuditReportTemplate,
                            type: 'fs',
                            ...tempObjs
                        });
                        setSpinLoad(false);
                        if (resTemp.success) {
                            notify(`模板初始化成功`, "success", 2000);
                            await getDesignTableName(actionTabs);
                            setTimeout(async () => {
                                if (!refsCommonCpasTable.current) return;
                                await refsCommonCpasTable.current?.CPASInit2(yearTableName, true);
                                await antTabsDetail();
                            }, 300);
                        } else {
                            await getDesignTableName(actionTabs);
                            setTimeout(async () => {
                                if (!refsCommonCpasTable.current) return;
                                await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
                            }, 300);
                            if (res.data.AuditReportTemplate) {
                                notify(`${resTemp.msg}`, "error", 2000);
                            } else {
                                notify(`请在首页组成部分信息内选择报告模板`, "warning", 2000);
                            }
                        }
                    }

                } else {
                    await getDesignTableName(actionTabs);
                    setTimeout(async () => {
                        if (!refsCommonCpasTable.current) return;
                        await refsCommonCpasTable.current.CPASInit2(yearTableName, false);
                        await antTabsDetail();
                    }, 300);
                }
                setIsInitBtn(false);
            } else {
                notify(`获取判断是否初始化失败！`, "error", 2000);
            }
        } catch (error) {
            notify(`获取判断是否初始化失败！`, "error", 2000);
        }
    };
    const add = async () => {
        if (!refsCommonCpasTable.current) return;
        setIsInitBtn(true);// 重要
        console.log(refsCommonCpasTable.current, '@@@ add');
        getAuditReportTemplate(false, "审定财务-资产减值准备情况表", 'addTabs');
        notify(`添加资产减值标签页，成功！`, "success", 2000);
    };


    const onEdit = (
        targetKey: React.MouseEvent | React.KeyboardEvent | string,
        action: 'add' | 'remove',
    ) => {
        if (action === 'add') {
            add();
        } else {
            refsDelte.current.show({
                title: "删除提醒",
                okCallback: () => {
                    remove(targetKey);
                }
            });


        }
    };



    const changeSpinAntTabs = async (newData: boolean, yearTableName: any) => {
        setSpinAntTabs(newData);
        setIsInitBtn(false);
        setValIndex('1');
        if (newData && refsCommonCpasTable.current) {
            await getDesignTableName('');
            refsCommonCpasTable.current.CPASInit2('审定财务-资产表', false);
        }
    }
    useEffect(() => {
        getAuditReportTemplate(true, "审定财务-资产表", '');
    }, []);

    useEffect(() => {
        if (pathname === '/ReportSys/approvedFinance' && query.tableName) {
            changeTabs(query.tableName);
        }
    }, [pathname, query]);

    return (<div className="trialBalance_whole">
        {/* {spinLoad && <SpinLoading loadString="正在初始化 ..." />} */}
        <PageLoading
            isOpen={spinLoad}
            isMaskClose={false}
            content={"正在初始化..."}
            width={200}
        />
        {spinAntTabs && <AntTabs defaultActiveKey="1"
            className="changeTabsHeight"
            type="editable-card"
            destroyInactiveTabPane={true}
            onChange={(val: string) => { changeTabsKey(val) }} activeKey={valIndex}
            onEdit={onEdit} hideAdd={hideAddBtn}
        >
            {
                antTabsData.map(item => (
                    <AntTabs.TabPane tab={
                        // <div onDoubleClick={() => handleDoubleClick(item.propsData.tableName, item.tabName)}>
                        <div>
                            <span>{item.tabName}
                                {item.isVerify && <span className="render-span"
                                    onClick={() => {
                                        if (refsCommonCpasTable.current) {
                                            refsCommonCpasTable.current.CPASOpenDetail();
                                        }
                                    }}>
                                    <WarningOutlined />
                                </span>}
                            </span>
                        </div>
                    }
                        key={item.tabKey} closable={item.closable} >
                        <CommonCpasTable CPASTableProps={item.propsData} CPASTableTabName={item.tabName}
                            isInitBtn={isInitBtn}
                            changeIsInitBtn={() => {
                                setIsInitBtn(false);
                            }}
                            biaoAllData={antTabsData}
                            excelParams={excelParams}
                            cpasChangeSpinAntTabs={(data: boolean, yearTableName: any) => { changeSpinAntTabs(data, yearTableName) }} antTabsTabPaneDetail2={() => antTabsDetail()}
                            ref={refsCommonCpasTable}
                            tableNameGroup={tableNameGroup}
                        />
                    </AntTabs.TabPane>
                ))
            }
        </AntTabs>}
        <DevPopup.Default ref={refsDelte} width={80} height={220}  >
            {() => {
                return <span>确定要执行此删除操作吗？</span>
            }}
        </DevPopup.Default>

        <FullNamePupop ref={refFullNamePupop} />

    </div>
    )
}
export default ApprovedFinance;
